package com.itlong.cloud.controller.config;

import org.apache.catalina.connector.Connector;
import org.apache.coyote.http11.Http11NioProtocol;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


/**
 * <desc>
 *      自定义tomcat容器参数调优。
 * </desc>
 *
 * @createDate 2020/11/25
 */
@Configuration
public class WebServerConfiguration {

    @Bean
    public ConfigurableServletWebServerFactory configurableServletWebServerFactory() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
        tomcat.addAdditionalTomcatConnectors(createConnector());
        return tomcat;
    }

    /**
     * <desc>
     *      多创建条Connector监听来设置调优，端口必须设置否则报错
     * </desc>
     *
     * @return
     * @author Wenchao.L
     * @createDate 2020-11-26
     */
    private Connector createConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
        connector.setPort(8185);
        // 最大工作线程数
        protocol.setMaxThreads(800);
        // 最大连接数
        protocol.setMaxConnections(10000);
        //关闭tomcatKeepAlive机制，防止TCP CLOSE_WAIT
        protocol.setMaxKeepAliveRequests(1);
        //HTTP POST提交无限制
        protocol.setMaxSavePostSize(-1);
        //线程池维持最小线程数,默认10
        protocol.setMinSpareThreads(4);
        //当所有线程都在使用时,建立连接的请求的等待队列长度,默认100
        protocol.setAcceptCount(1000);
        return connector;
    }
}
